import { createRouter, createWebHistory } from 'vue-router'

// 页面组件（根据你项目里的实际路径调整）
import Login from '@/pages/auth/Login.vue'
import Register from '@/pages/auth/Register.vue'
import AccountLayout from '@/pages/account/AccountLayout.vue'      // 个人中心布局（含侧边栏）
import Profile from '@/pages/account/Profile.vue'            // 个人资料页
import Security from "@/pages/account/Security.vue";
import Subscription from '@/pages/account/Subscription.vue'  // 订阅页
import MailAccounts from '@/pages/account/MailAccounts.vue'  // 邮箱账号
import Whitelist from '@/pages/account/Whitelist.vue'        // 白名单
import Usage from '@/pages/account/Usage.vue'                // 用量

import { getToken, isTokenValid } from '@/utils/jwt'

// 路由表
const routes = [
    // 登录 / 注册（公开路由）
    { path: '/login', name: 'AuthLoginPage', component: Login, meta: { public: true } },
    { path: '/register', name: 'AuthRegisterPage', component: Register, meta: { public: true } },

    // 个人中心（需要登录）
    {
        path: '/account',
        component: AccountLayout,
        children: [
            { path: '', redirect: '/account/profile' },           // 进入 /account 默认到个人资料
            { path: 'profile', name: 'AccountProfilePage', component: Profile },
            {path: 'security', name: 'AccountSecurityPage', component: Security},
            { path: 'subscription', name: 'AccountSubscriptionPage', component: Subscription },
            { path: 'mail', name: 'AccountMailAccountsPage', component: MailAccounts },
            { path: 'whitelist', name: 'AccountWhitelistPage', component: Whitelist },
            { path: 'usage', name: 'AccountUsagePage', component: Usage },
        ]
    },

    // 根路径：占位，实际跳转由 beforeEach 动态决定
    { path: '/', name: 'Root', component: { template: '<div />' } },

    // 兜底：未知路径 → 根路径（再由守卫判断去向）
    { path: '/:pathMatch(.*)*', redirect: '/' }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

/**
 * 全局前置守卫：
 * 1) 访问 "/" 时，按是否有有效 token 选择去 /account 或 /login
 * 2) 对非 public 路由做登录态拦截；已登录用户访问 /login /register 时自动去 /account
 */
router.beforeEach((to) => {
    const token = getToken()
    const authed = isTokenValid(token)

    // 访问根路径：动态分流
    if (to.path === '/') {
        return authed ? { path: '/account' } : { path: '/login' }
    }

    // 公开路由：/login /register
    if (to.meta?.public) {
        return authed ? { path: '/account' } : true
    }

    // 需要鉴权的路由
    if (!authed) {
        return { path: '/login', query: { redirect: to.fullPath } }
    }

    return true
})

export default router
